﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Resources;
using System.Text;
using System.Web;
using System.Web.Mvc;
using SPMS.Common;
using SPMS.Common.Pinyin;
using SPMS.Web.Models;

namespace SPMS.Web.Controllers
{
    /// <summary>
    /// 辅助控制器
    /// </summary>
    [AuthorizeEx]
    public class CommonController : Controller
    {
        #region ---Actions

        /// <summary>
        /// 获得临时图片。
        /// </summary>
        /// <param name="model">临时文件模型。</param>
        /// <returns>执行结果。</returns>
        public FileResult GetTempImage(TempImageModel model)
        {
            //获得图片格式
            ImageFormat format = FileUploadHelper.GetImageFormat(model.Format, ImageFormat.Jpeg);

            //获得临时图片文件数据
            byte[] imageData = FileUploadHelper.GetTempImage(model.FileID, model.Width, model.Height, format);

            //获得扩展名
            string extension = FileUploadHelper.GetImageExtension(format);

            //返回文件结果
            return this.File(imageData, FileUploadHelper.GetImageMIME(format), Path.Combine("temp", extension));
        }

        /// <summary>
        /// 获得字符串资源。
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public JavaScriptResult Resources()
        {
            //判断客户端资源是否已经初始化
            if (string.IsNullOrEmpty(s_ClientResources))
            {
                //创建字符串构建器
                StringBuilder builder = new StringBuilder();

                //添加脚本头
                builder.AppendLine("(");
                builder.AppendLine("    function ()");
                builder.AppendLine("    {");
                builder.AppendLine("        'use strict';");
                builder.AppendLine("        var _spms = window.spms;");
                builder.AppendLine("        if ( typeof _spms == 'undefined' )");
                builder.AppendLine("        {");
                builder.AppendLine("            _spms = {};");
                builder.AppendLine("            window.spms = _spms;");
                builder.AppendLine("        }");
                builder.AppendLine("        _spms.resources =");
                builder.AppendLine("        {");

                //获得资源
                ResourceSet resources = SPMS.Web.Properties.Resources.ResourceManager.GetResourceSet(System.Globalization.CultureInfo.CurrentUICulture, true, true);

                //判断资源是否存在
                if (null != resources)
                {
                    //用于保存字符串值
                    string value = string.Empty;

                    //是否需要添加都好
                    bool isNeedComma = false;

                    //循环输出资源
                    foreach (DictionaryEntry entry in resources)
                    {
                        //判断是否为字符串资源
                        if (entry.Value is string && null != entry.Value)
                        {
                            //判断是否需要添加逗号
                            if (isNeedComma)
                            {
                                //添加逗号
                                builder.Append(",");
                                //添加行
                                builder.AppendLine("");
                            }

                            //获得字符串资源
                            value = entry.Value.ToString();

                            //替换掉单引号
                            value = value.Replace("'", "\'");

                            //输出字符串资源
                            builder.AppendFormat("            {0}: '{1}'", entry.Key, value);

                            //设置需要添加逗号
                            isNeedComma = true;
                        }
                    }

                    //清除引用避免资源被释放
                    resources = null;

                    //添加脚本尾
                    builder.AppendLine("");
                    builder.AppendLine("        };");
                    builder.AppendLine("    }");
                    builder.AppendLine(")();");
                }

                //保存资源
                s_ClientResources = builder.ToString();
            }

            //返回脚本
            return JavaScript(s_ClientResources);
        }

        /// <summary>
        /// 上传临时文件
        /// </summary>
        /// <returns>操作结果。</returns>
        /// <remarks></remarks>
        [HttpPost]
        [JsonHandleError]
        public ActionResult UploadTempFile()
        {
            //获得会话编号
            Guid sessionID = FormsAuthenticationHelper.GetSystemSessionID();

            //上传临时文件
            Guid[] tempFiles = FileUploadHelper.UploadTempFile(sessionID, this.Request);

            //返回结果
            return new JsonResultEx
            (
                new JsonResultViewModel()
                {
                    success = true,
                    data = tempFiles.ToArray()
                },
                JsonRequestBehavior.AllowGet
            );
        }

        /// <summary>
        /// 上传临时图片文件
        /// </summary>
        /// <param name="model">图片上传模型。</param>
        /// <returns>
        /// 操作结果。
        /// </returns>
        [HttpPost]
        [JsonHandleError]
        public ActionResult UploadTempImage(TempImageModel model)
        {
            //获得会话编号
            Guid sessionID = FormsAuthenticationHelper.GetSystemSessionID();

            //判断是否需要处理图片
            if (model.Width.HasValue || model.Height.HasValue || !string.IsNullOrEmpty(model.Format))
            {
                //创建处理委托
            }

            //上传临时文件
            Guid[] tempFiles = FileUploadHelper.UploadTempFile(sessionID, this.Request);

            //返回结果
            return new JsonResultEx
            (
                new JsonResultViewModel()
                {
                    success = true,
                    data = tempFiles.ToArray()
                },
                JsonRequestBehavior.AllowGet
            );
        }

        /// <summary>
        /// 将指定的汉字转化为拼音。
        /// </summary>
        /// <param name="source">要转换的汉字。</param>
        /// <returns>将指定的汉字转换而成的拼音。</returns>
        /// <remarks></remarks>
        [HttpGet]
        [JsonHandleError]
        public JsonResult ConvertToPinYin(string source)
        {
            //用于保存拼音
            string pinyin = string.Empty;

            //判断源字符串是否有效
            if (!string.IsNullOrEmpty(source))
            {
                //转换拼音
                pinyin = PinYinConverter.ConvertToPinYin(source);
            }

            //返回结果
            return this.JsonEx(true, (object)pinyin);
        }

        #endregion

        #region ---Private Method

        /// <summary>
        /// 处理图片。
        /// </summary>
        /// <param name="source">包含要处理图片数据的<see cref="System.IO.Stream"/>。</param>
        /// <param name="state">包含处理参数的对象。</param>
        /// <returns></returns>
        private static System.IO.Stream ProcessImage(System.IO.Stream source, object state)
        {
            //转换为图片处理参数
            TempImageModel model = state as TempImageModel;

            //判断是否指定了处理参数
            if (null == model)
            {
                //直接返回原始流
                return source;
            }

            //用于保存宽度
            int width = 0;

            //判断是否指定了宽度
            if (model.Width.HasValue)
            {
                width = model.Width.Value;
            }

            //用于保存高度
            int height = 0;

            //判断是否指定了高度
            if (model.Height.HasValue)
            {
                height = model.Height.Value;
            }

            //用于保存格式
            ImageFormat format = FileUploadHelper.GetImageFormat(model.Format, ImageFormat.Jpeg);

            //创建位图
            using (Bitmap tempImage = (Bitmap)Bitmap.FromStream(source))
            {
                //处理图片
                using (Bitmap image = FileUploadHelper.ProcessImage(tempImage, width, height, 0, format, Color.White))
                {
                    //创建内存流
                    MemoryStream destStream = new MemoryStream();

                    //保存图片
                    image.Save(destStream, format);

                    //移动到开头
                    destStream.Seek(0, SeekOrigin.Begin);

                    //返回流
                    return destStream;
                }
            }
        }

        #endregion

        #region ---Field

        /// <summary>
        /// 当前客户端资源
        /// </summary>
        private static string s_ClientResources = null;

        #endregion
    }
}
